/*
 * $AIST_Release: 0.9.0 $
 * Copyright 2011 Information Technology Research Institute, National
 * Institute of Advanced Industrial Science and Technology
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package generator

import java.io.File

object StaticInitializer {

  /**
   * Generates Java source file where static variables are defined.
   */
  def genVariablesSrc(dir: File, svars: List[(String, String, String)]): (File, String) = {
    val className = "GeneratedStaticVariables"
    val ifs = List("Helpers.StaticVariables", "Serializable")

    Generator.genSrc(dir, className, None, ifs) { pw =>
      // Field
      for ((dataType, name, _) <- svars) {
        pw.println("public %s %s;".format(dataType, name))
      }

      // Constructor
      pw.println("public %s(Descriptor[] messages) {".format(className))
      pw.println("Converters converters = new Converters(messages);")

      for ((_, name, value) <- svars) {
        pw.println("%s = (%s);".format(name, value))
      }

      pw.println("}")

      // Empty Constructor(for Serialize)
      pw.println("public %s() {}".format(className))
    }
  }

  /**
   * Generates Java source file where table arguments are defined.
   */
  def genTablesSrc(dir: File, tables: List[Table]): (File, String) = {

    val className = "GeneratedTableArguments"
    val tableFieldName = "tableArgs"

    Generator.genSrc(dir, className, None, List("Helpers.TableArguments")) { pw =>
      pw.println("public Map<Integer, Object[]> %s = new HashMap<Integer, Object[]>();".format(tableFieldName))
      pw.println("public %s(GeneratedStaticVariables statics) {".format(className))
      for (table <- tables) {
        pw.println("{")
        pw.println("Object[] tmp = new Object[%d];".format(table.args.size))

        for ((arg, n) <- table.args.iterator.zipWithIndex) {
          pw.println("tmp[%d] = %s;".format(n, arg))
        }

        pw.println("%s.put(%d, tmp);".format(tableFieldName, table.id))
        pw.println("}")
      }
      pw.println("}")
      pw.println("@Override public Map<Integer, Object[]> getValues() {\n" + 
                 "return %s;\n".format(tableFieldName) +
                 "}")
        
    }
  }
}
